﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataObject.DataAccess;
using DataObject.Database;

public partial class Pages_Reservation_ReservationEdit : Page
{
    public const string Germany = "Germany";

    #region Properties

    public DateTime DepDate
    {
        get
        {
            if (ViewState["DepDate"] != null)
                return Convert.ToDateTime(ViewState["DepDate"], CultureInfo.InvariantCulture);
            throw new NullReferenceException();
        }
        set { ViewState["DepDate"] = value; }
    }

    public DateTime BoardDate
    {
        get
        {
            if (ViewState["BoardDate"] != null)
                return Convert.ToDateTime(ViewState["BoardDate"], CultureInfo.InvariantCulture);
            throw new NullReferenceException();
        }
        set { ViewState["BoardDate"] = value; }
    }

    public string BoatID
    {
        get
        {
            if (ViewState["BoatID"] != null) return ViewState["BoatID"].ToString();
            throw new NullReferenceException();
        }
        set { ViewState["BoatID"] = value; }
    }

    public int NoOfNights
    {
        get
        {
            if (ViewState["NoOfNights"] != null) return Convert.ToInt32(ViewState["NoOfNights"]);
            throw new NullReferenceException();
        }
        set { ViewState["NoOfNights"] = value; }
    }

    public Guid ReservationID
    {
        get
        {
            if (String.IsNullOrEmpty(Request["ReservationID"]))
                return Guid.Empty;
            return new Guid(Request["ReservationID"]);
        }
    }

    #region Properties

    private object _boatList;

    private object _countryList;

    private object _routeList;

    public object BoatList
    {
        get
        {
            if (_boatList == null)
            {
                _boatList = (HttpContext.Current.Cache["BoatList"] as List<object>);
                if (_boatList == null)
                {
                    _boatList = BoatDAO.CreateInstant().GetAllBoats();
                    HttpContext.Current.Cache.Insert("BoatList", _boatList);
                }
            }
            return _boatList;
        }
        set { HttpContext.Current.Cache.Insert("BoatList", _boatList); }
    }

    public object CountryList
    {
        get
        {
            if (_countryList == null)
            {
                _countryList = (HttpContext.Current.Cache["CountryList"] as List<object>);
                if (_countryList == null)
                {
                    _countryList = ParameterDAO.CreateInstant()
                        .SelectListItem(null, "Country", "", "", null, true, new HashSet<string>());
                    HttpContext.Current.Cache.Insert("CountryList", _countryList);
                }
            }
            return _countryList;
        }
        set { HttpContext.Current.Cache.Insert("CountryList", _countryList); }
    }

    public object RouteList
    {
        get
        {
            if (_routeList == null)
            {
                _routeList = (HttpContext.Current.Cache["RouteList"] as List<Route>);
                if (_routeList == null)
                {
                    _routeList = RouteDAO.CreateInstant().GetAllRoutes();
                    HttpContext.Current.Cache.Insert("RouteList", _routeList);
                }
            }
            return _routeList;
        }
        set { HttpContext.Current.Cache.Insert("RouteList", _routeList); }
    }

    #endregion

    #endregion

    /// <summary>
    ///     Load combobox
    /// </summary>
    private void LoadCombo()
    {
        // Load country list
        ddlCountry.DataSource = CountryList;
        ddlCountry.DataTextField = "Value";
        ddlCountry.DataValueField = "ParamID";
        ddlCountry.DataBind();

        // Load route list
        // Load route list
        foreach (Route item in RouteList as IList<Route>)
        {
            string routeCode = item.RouteNumber +
                               (item.SubRouteCode.HasValue && item.SubRouteCode != ' '
                                   ? "-" + item.SubRouteCode
                                   : String.Empty);
            var listItem = new ListItem
            {
                Value = routeCode,
                Text = item.RouteName
            };
            listItem.Attributes.Add("RouteNumber", item.RouteNumber.ToString(CultureInfo.InvariantCulture));
            listItem.Attributes.Add("SubRoute", item.SubRouteCode.ToString());
        }

        ddlReservationCurrency.Items.AddRange(DropDownListHelper.Currencies);

        // Get exchange rate
        //new OBS.Get().GetExchange(define.DefaultCurrency, DateTime.Now.ToShortDate());
    }

    #region Events

    /// <summary>
    ///     Page load
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (ReservationID == Guid.Empty)
        {
            // Return to reservation list
            Response.Redirect("ReservationList.aspx");
        }

        if (!IsPostBack)
        {
            LoadCombo();

            Reservation reservationEntity = ReservationDAO.CreateInstant().GetReservationById(ReservationID);
            if (reservationEntity != null)
            {
                BoatID = reservationEntity.BoatID;
                BoatEntity item = BoatDAO.CreateInstant().GetBoat(BoatID);
                if (item != null)
                    LiteralBoat.Text = item.BoatName;

                // Operator Info
                txtBookingCode.Text = reservationEntity.ReservationCode;
                lblCreatedBy.Text = reservationEntity.CreatedByID;
                lblCreationDate.Text = reservationEntity.CreationDate.ToLongDate();
                lblModifiedBy.Text = reservationEntity.ModifiedByID;
                lblModifiedDate.Text = reservationEntity.ModifiedDate.ToLongDate();

                // Reservation Info
                ddlBookingStatus.SelectedValue = reservationEntity.Status.ToString(CultureInfo.InvariantCulture);

                DepDate = reservationEntity.DepartureDate;
                BoardDate = reservationEntity.CheckInDate;
                litDepDate.Text = DepDate.ToShortDate();
                litBoardDate.Text = BoardDate.ToShortDate();

                if (DepDate.Date < DateTime.Today && ddlBookingStatus.SelectedIndex != 1)
                    ddlBookingStatus.Items.RemoveAt(1);

                // Num Of Cabins, Pax, Nights
                NoOfNights = reservationEntity.NumOfNights;
                LiteralDateNumber.Text = NoOfNights.ToString(CultureInfo.InvariantCulture);
                LiteralCabinNumber.Text = reservationEntity.NumOfCabins.ToString(CultureInfo.InvariantCulture);
                txtTotalClients.Text = reservationEntity.NumOfPax.ToString(CultureInfo.InvariantCulture);

                hdfBoatID.Value = reservationEntity.BoatID;

                // Amount
                chkShuttle.Checked = reservationEntity.IsShuttle;

                txtShuttlePrice.Text = reservationEntity.ShuttlePrice.ToString(define.DecimalFormat);
                txtBoatingFee.Text = reservationEntity.CruisePackage.ToString(define.DecimalFormat);
                // -----------------
                decimal total = reservationEntity.ShuttlePrice + reservationEntity.ExtraService +
                                reservationEntity.CruisePackage;
                txtTotal.Text = total.ToString(define.DecimalFormat);

                // Currency and exchange rate
                ddlReservationCurrency.SelectedValue = reservationEntity.CruiseCurrency.ToString(CultureInfo.InvariantCulture);
                txtReservationRate.Value = reservationEntity.CruiseRate.ToString(define.DecimalFormat);

                // Sub-Total
                decimal subTotal = total*reservationEntity.CruiseRate;
                txtSubTotal.Text = subTotal.ToString(define.DecimalFormat);
                txtPaid.Text = reservationEntity.Paid.ToString(define.DecimalFormat);
                txtPaymentFee.Text = reservationEntity.PaidFee.ToString(define.DecimalFormat);
                txtDeposit.Text = reservationEntity.Deposit.ToString(define.DecimalFormat);
                txtBalance.Text = reservationEntity.Balance.ToString(define.DecimalFormat);

                txtEmailConfirmation.Text = reservationEntity.ConfirmationEmail;

                chkPaidComplete.Checked = reservationEntity.PaidStatus;
                txtNote.Text = HttpUtility.HtmlDecode(reservationEntity.Note);

                if (reservationEntity.Alarm.HasValue)
                {
                    txtAlarm.Text = reservationEntity.Alarm.Value.ToShortDate();
                }

                // Contact Info
                Guest guestEntity = GuestDAO.CreateInstant().GetGuestById(reservationEntity.GuestID);
                if (guestEntity != null)
                {
                    txtAddressLine1.Text = guestEntity.AddressLine1;
                    txtAddressLine2.Text = guestEntity.AddressLine2;
                    lblAgent.Text = guestEntity.FullName;
                    lblCompanyName.Text = guestEntity.CompanyName;
                    txtCity.Text = guestEntity.City;
                    txtEmail.Text = guestEntity.Email;
                    txtFax.Text = guestEntity.Fax;
                    txtFirstName.Text = guestEntity.FirstName;
                    txtLastName.Text = guestEntity.Lastname;
                    txtTel.Text = guestEntity.Tel;
                    ddlTitle.SelectedValue = guestEntity.Title;
                    txtZipCode.Text = guestEntity.ZipCode;

                    hdfAgentID.Value = guestEntity.GuestID;
                    hdfCharterPrice.Value = "0";

                    if (guestEntity.GuestType == 0)
                    {
                        // Agent Type
                        divWalkIn.Visible = false;

                        // Don't allow edit the agent info
                        txtAddressLine1.Enabled = false;
                        txtAddressLine2.Enabled = false;
                        txtCity.Enabled = false;
                        txtEmail.Enabled = false;
                        txtFax.Enabled = false;
                        txtFirstName.Enabled = false;
                        txtLastName.Enabled = false;
                        txtTel.Enabled = false;
                        ddlTitle.Enabled = false;
                        txtZipCode.Enabled = false;
                        ddlCountry.Enabled = false;
                    }
                    else
                    {
                        // Walk-In
                        divAgent.Visible = false;
                    }

                    ParameterEntity param = ParameterDAO.CreateInstant().GetParameterById(guestEntity.CountryID);
                    if (item != null)
                        ddlCountry.SelectedValue = param.ParamID.ToString(CultureInfo.InvariantCulture);

                    if (reservationEntity.IsCharter)
                    {
                        List<AgentPricesEntity> agentPrices =
                            AgentPricesDAO.CreateInstant().GetPrices(guestEntity.GuestID);
                        AgentPricesEntity agentPricesCharterEntity = agentPrices.SingleOrDefault(n => n.Boat != null
                                                                                                      &&
                                                                                                      n.Boat.ToLower()
                                                                                                          .Equals(
                                                                                                              reservationEntity
                                                                                                                  .BoatID
                                                                                                                  .ToLower
                                                                                                                  ())
                                                                                                      &&
                                                                                                      n.AgentID.ToLower()
                                                                                                          .Equals(
                                                                                                              reservationEntity
                                                                                                                  .GuestID
                                                                                                                  .ToLower
                                                                                                                  ())
                                                                                                      &&
                                                                                                      n.PriceType.Equals
                                                                                                          ("charter"));
                        if (agentPricesCharterEntity != null)
                        {
                            hdfCharterPrice.Value = agentPricesCharterEntity.Price.ToString(CultureInfo.InvariantCulture);
                        }
                    }
                }

                var hs = new HashSet<string> {"CabinID ASC"};
                List<ReservationDetail> ls = ReservationDetailDAO.CreateInstant()
                    .SelectListItem(null, reservationEntity.ReservationID, null, "", null, null, null, "", hs);
                rpt.DataSource = ls;
                rpt.DataBind();
            }
        }
    }

    /// <summary>
    ///     Bound reservation detail
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            var txtRepresentative = (TextBox) e.Item.FindControl("txtRepresentative");
            var txtCabinNumber = (TextBox) e.Item.FindControl("txtCabinNumber");
            var txtPrice = (TextBox) e.Item.FindControl("txtPrice");
            var txtCabinID = (TextBox) e.Item.FindControl("txtCabinID");
            var txtNoteDetail = (TextBox) e.Item.FindControl("txtNote");

            var litBoatName = (Literal) e.Item.FindControl("litBoatName");

            var ddlStatus = (DropDownList) e.Item.FindControl("ddlStatus");
            var ddlBlockDates = (DropDownList) e.Item.FindControl("ddlBlockDates");
            var ddlBedrooms = (DropDownList) e.Item.FindControl("ddlBedrooms");
            var ddlNumberClient = (DropDownList) e.Item.FindControl("ddlNumberClient");

            var item = (ReservationDetail) e.Item.DataItem;
            CabinEntity cabin = CabinDAO.CreateInstant().GetCabin(item.CabinID);
            CabinStatusEntity cabinStatus = CabinStatusDAO.CreateInstant()
                .GetCabinStatus(item.RDID, item.CabinID, BoardDate);
            BoatEntity boat = BoatDAO.CreateInstant().GetBoat(cabin.BoatID);

            if (cabinStatus != null)
                ddlBlockDates.SelectedValue = cabinStatus.BlockDates.ToString(CultureInfo.InvariantCulture);
            ddlNumberClient.SelectedValue = item.NumOfPeople.ToString(CultureInfo.InvariantCulture);
            ddlBedrooms.SelectedValue = item.Status.ToString(CultureInfo.InvariantCulture);
            ddlStatus.SelectedValue = item.CabinStatus.ToString(CultureInfo.InvariantCulture);

            txtCabinNumber.Text = cabin.CabinNumber;
            txtCabinID.Text = cabin.CabinID.ToString(CultureInfo.InvariantCulture);
            txtRepresentative.Text = item.Representative;
            txtPrice.Text = (item.UnitPrice ?? 0).ToString(define.DecimalFormat);

            litBoatName.Text = boat.BoatName;

            ddlBlockDates.Attributes.Add("class", "blockdate blockdate-" + e.Item.ItemIndex);
            ddlBlockDates.Attributes.Add("index", "" + e.Item.ItemIndex);
            ddlNumberClient.Attributes.Add("class", "numberclient numberclient-" + e.Item.ItemIndex);
            ddlNumberClient.Attributes.Add("index", "" + e.Item.ItemIndex);
            ddlBedrooms.Attributes.Add("class", "typeofcabin typeofcabin-" + e.Item.ItemIndex);
            ddlBedrooms.Attributes.Add("index", "" + e.Item.ItemIndex);

            txtRepresentative.Attributes.Add("class", "representative representative-" + e.Item.ItemIndex);
            txtRepresentative.Attributes.Add("index", "" + e.Item.ItemIndex);
            txtCabinNumber.Attributes.Add("class", "cabinnumber cabinnumber-" + e.Item.ItemIndex);
            txtCabinNumber.Attributes.Add("index", "" + e.Item.ItemIndex);
            txtCabinID.Attributes.Add("class", "cabinid cabinid-" + e.Item.ItemIndex);
            txtCabinID.Attributes.Add("index", "" + e.Item.ItemIndex);
            txtPrice.Attributes.Add("class", "auto price cabinprice-" + e.Item.ItemIndex);
            txtPrice.Attributes.Add("index", "" + e.Item.ItemIndex);
            txtNoteDetail.Attributes.Add("class", "notedetail notedetail-" + e.Item.ItemIndex);
            txtNoteDetail.Attributes.Add("index", "" + e.Item.ItemIndex);
        }
    }

    #endregion
}